package service

import (
	"context"
	"fmt"
	"math/rand"
	"time"
	"user-service/basic/config"
	__ "user-service/basic/proto"
	"user-service/handler/model"
)

type Server struct {
	__.UnimplementedUserServer
}

func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	code := rand.Intn(9000) + 100
	//sms, _ := pkg.SendSms(strconv.Itoa(code),in.Phone)
	//if *sms.Body.Code!="OK" {
	//	return nil, fmt.Errorf(*sms.Body.Message)
	//}
	config.Rdb.Set(config.Ctx, "sendSms"+in.Phone, code, time.Minute*5)
	return &__.SendSmsResp{}, nil
}

// SayHello implements helloworld.GreeterServer
func (s *Server) GetPhoneByPhone(_ context.Context, in *__.GetPhoneByPhoneReq) (*__.GetPhoneByPhoneResp, error) {
	var user model.User
	if err := user.GetPhoneByPhone(config.DB, in.Phone); err != nil {
		return nil, err
	}
	return &__.GetPhoneByPhoneResp{
		Phone:  user.Phone,
		UserId: int64(user.ID),
	}, nil
}
func (s *Server) CreatePhone(_ context.Context, in *__.CreatePhoneReq) (*__.CreatePhoneResp, error) {
	result, _ := config.Rdb.Get(config.Ctx, "sendSms"+in.Phone).Result()
	if result != in.Code {
		return nil, fmt.Errorf("该验证码已失效")
	}
	users := model.User{
		Phone: in.Phone,
	}
	if err := users.CreateUser(config.DB); err != nil {
		return nil, err
	}

	return &__.CreatePhoneResp{
		UserId: int64(users.ID),
	}, nil
}
